package com.tanhua.dubbo.Api;

import com.tanhua.dubbo.api.FriendApi;
import com.tanhua.model.mongo.Friend;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @author 刘付磊
 * @date 2021/11/21 0021
 */
@DubboService
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(Long userId, Long friendId) {
        //1.保存自己的好友数据
        //1.1判断好友关系是否存在
        Query query = Query.query(Criteria.where("userId").is(userId).and("friendId").is(friendId));
        if (!template.exists(query, Friend.class)){
            //1.2 如果不存在 保存
            Friend friend = new Friend();
            friend.setFriendId(userId);
            friend.setUserId(friendId);
            friend.setCreated(System.currentTimeMillis());
            template.save(friend);
        }
        //2.保存好友的好友数据
        //1.1判断好友关系是否存在
        //1.2 如果不存在 保存
        Query query2 = Query.query(Criteria.where("userId").is(friendId).and("friendId").is(userId));
        if (!template.exists(query, Friend.class)){
            //1.2 如果不存在 保存
            Friend friend = new Friend();
            friend.setFriendId(friendId);
            friend.setUserId(userId);
            friend.setCreated(System.currentTimeMillis());
            template.save(friend);
        }
    }

    //查询好友id
    @Override
    public List<Friend> findByFriends(Integer page, Integer pagesize, Long userId) {
        Criteria criteria = Criteria.where("userId").is(userId);
        Query query =Query.query(criteria).limit(pagesize).skip((page-1)*pagesize).with(Sort.by(Sort.Order.desc("created")));
        List<Friend> friends = template.find(query, Friend.class);
        return friends;
    }
}
